<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"
          ><i class="el-icon-arrow-left" />返回</span
        >
        <span>|</span>
        <span>{{ id ? "编辑企业信息" : "添加企业 " }}</span>
      </div>
      <div class="right">{{ userDetails.userName }}</div>
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form
            ref="ruleForm"
            label-width="100px"
            :model="addForm"
            :rules="addFormRules"
          >
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <!-- el-select v-model 要绑定的值，el-option把value的值给到v-model的值 -->
              <el-select v-model="addForm.industryCode">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :label="item.industryName"
                  :value="item.industryCode"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
              <!-- action是必传属性，代表文件上传路径，一般不用 -->
              <!-- action就算不用，也需要配置，用“#”-->
              <!-- :http-request="uploadImage" 自定义配置 -->
              <!-- list-type:上传组件样式的控制 -->
              <!-- on-preview：预览 -->
              <!-- limit 上传的最大文件数 -->
              <!-- on-success：上传成功 -->
              <!-- on-exceed：上传文件个数超出限制，自动执行这个钩子函数 -->
              <!-- on-remove：移除文件时触发的钩子函数 -->
              <el-upload
                class="upload-demo"
                action="#"
                :http-request="uploadImage"
                :before-upload="beforeUpload"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  支持扩展名：.png .jpg .jpeg,文件大小不可超过5M
                </div>
              </el-upload>
              <img
                :src="addForm.businessLicenseUrl"
                alt=""
                v-if="id"
                style="height: 400px; width: 500px; object-fit: cover"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="reset">重置</el-button>
        <el-button type="primary" @click="addEnterprise">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import {
  reqGetIndustryListAPI,
  reqAddNewEnterpriseAPI,
  enterpriseDetailAPI,
  reqEditAPI,
} from "@/api/enterprise";
import { reqUploadAPI } from "@/api/common";
import { mapState } from "vuex";
export default {
  data() {
    return {
      addForm: {
        name: "", // 企业名称
        legalPerson: "", // 法人
        registeredAddress: "", // 注册地址
        industryCode: "", // 所在行业
        contact: "", // 企业联系人
        contactNumber: "", // 联系人电话
        businessLicenseUrl: "", // 营业执照url
        businessLicenseId: "", // 营业执照id
      },
      industryList: [],
      addFormRules: {
        name: [
          {
            required: true,
            message: "请输入企业名称",
            trigger: "blur",
          },
        ],
        legalPerson: [
          {
            required: true,
            message: "请输入法人姓名",
            trigger: "blur",
          },
        ],
        registeredAddress: [
          {
            required: true,
            message: "请输入注册地址",
            trigger: "blur",
          },
        ],
        industryCode: [
          {
            required: true,
            message: "请输入行业代码",
            trigger: "blur",
          },
        ],
        contact: [
          {
            required: true,
            message: "请输入联系人",
            trigger: "blur",
          },
        ],
        contactNumber: [
          {
            required: true,
            message: "请输入联系人电话",
            trigger: "blur",
          },
        ],
        businessLicenseId: [
          {
            required: true,
            message: "请输入营业执照编号",
            trigger: "blur",
          },
        ],
      },
    };

  },

  created() {
    if (this.id) {
      // 如果有id就回显
      this.addEnterpriseDetailAPI();
    }
    this.getIndustryList();
  },
  methods: {
    // 获取行业列表
    async getIndustryList() {
      const res = await reqGetIndustryListAPI();
      console.log(res);
      this.industryList = res.data;
      console.log(this.industryList);
    },
    // 上传图片
    async uploadImage({ file }) {
      //第二步：new FormData 对象
      const formData = new FormData();
      //当前接口需要两个参数 1.文件 2.文件类型
      //追加数据，使用append方法  “file” <- file
      formData.append("file", file);
      formData.append("type", 1);
      const res = await reqUploadAPI(formData);
      console.log(res);
      this.addForm.businessLicenseUrl = res.data.url;
      this.addForm.businessLicenseId = res.data.id;
      
      //form表单的validate方法只可以校验常规元素，而upload不是常规元素，因此需要单独校验
      this.$refs.ruleForm.validateField("businessLicenseUrl");
    },
    // 拿到上传时的file
    beforeUpload(file) {
      const imgType = ["image/png", "image/jpg", "image/jpeg"];
      // 检验上传文件类型是否属于以上类型
      const type = imgType.includes(file.type);
      // 检验大小是否超过5m
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (type && isLt5M) {
        return true;
      } else {
        this.$message.error("上传文件不符合要求，请重新上传！");
        return false;
      }
    },
    // 回显企业信息
    async addEnterpriseDetailAPI() {
      const res = await enterpriseDetailAPI(this.id);
      console.log(res, "企业信息回显");
      this.addForm = res.data;
      console.log(this.addForm, "企业信息回显");
    },
    // 兜底校验
    async addEnterprise() {
      this.$refs.ruleForm.validate(async (flag) => {
        if (!flag) {
          this.$message.error("请填写完整信息！");
          return;
        }
        if (this.id) {
          // 执行新增逻辑
          // 入参信息有错误，需要删除几个字段
          delete this.addForm.businessLicenseName;
          delete this.addForm.industryName;
          delete this.addForm.rent;
          await reqEditAPI(this.addForm);
          this.$message.success("修改成功");
        } else {
          await reqAddNewEnterpriseAPI(this.addForm);
          this.$message.success("添加成功");
        }
        this.$router.back();
      });
    },
    // 重置
    reset() {
      this.$refs.ruleForm.resetFields();
    },
    // 获取企业详情
  },
  computed: {
    id() {
      return this.$route.query.id;
    },
    ...mapState('user',["userDetails"])
  },
};
</script>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form {
          display: flex;
          flex-wrap: wrap;
          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
